package com.phpxiu.app.okhttp.param;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;

/**
 * @file
 * @brief 自定义封装okhttp post方式的参数
 * @author 吴金洲
 * @note 自定义封装okhttp post方式的参数
 * post方式的参数不需要urlEncoder，如果参数值含有中文或已经转化的请设置参数构造参数urlEncoder为false
 *
 */
public class OKHttpParam extends LinkedHashMap<String,Object> {
    /**
     * 自定义TypeAdapter，字符串类型以UTF8输出
     */
    public final static TypeAdapter<String> UTF8=new OKHttpParamUTF8();
    private final static Gson GSON_UTF8 =new GsonBuilder().registerTypeAdapter(String.class,UTF8).create();
    private final static Gson GSON=new Gson();
    private boolean urlEncoder=true;
    public static OKHttpParam builder(){
        OKHttpParam param=new OKHttpParam();
        param.put("platform", "android");
        return param;
    }

    public static OKHttpParam builder(boolean urlEncoder){
        OKHttpParam param=new OKHttpParam();
        param.setUrlEncoder(urlEncoder);
        param.put("platform", "android");
        return param;
    }

    @Override
    public Object put(String key, Object value) {
        if(isUrlEncoder()) {
            try {
                if (value instanceof String) {
                    value = URLEncoder.encode(value.toString(), "UTF-8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return super.put(key, value);
    }

    /**
     * 转换为字符串
     * @return
     */
    public String jsonParam(){
        if(isUrlEncoder()) {
            //return GSON_UTF8.toJson(this);
        }else{
            //return GSON.toJson(this);
        }
        return GSON.toJson(this);
    }

    public boolean isUrlEncoder() {
        return urlEncoder;
    }

    public void setUrlEncoder(boolean urlEncoder) {
        this.urlEncoder = urlEncoder;
    }
}
